package com.toman.ui.work.workplan;

import android.content.res.ColorStateList;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.lzy.okhttputils.OkHttpUtils;
import com.toman.Enum.BaseEnum;
import com.toman.Enum.PermEnum;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.JavaBean.DeviceHouseMonthDayPlanEntity;
import com.toman.JavaBean.DeviceHouseMonthPlanEntity;
import com.toman.MyApplication;
import com.toman.R;
import com.toman.Util.BaseNetUtil;
import com.toman.Util.DoubleMarkerView;
import com.toman.Util.IntentUtils;
import com.toman.Util.JsonExcludeNull;
import com.toman.Util.NetworkUtils;
import com.toman.Util.PermissonUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.TimeUtil;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.Util.XYMarkerView;
import com.toman.toolbar.ToolBarActivity;
import com.toman.ui.work.management.ProblemFeedbackActivity;
import com.toman.widget.WaveView;
import com.toman.widget.callback.StringLoadingCallback;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.refreshlayout.BGANormalRefreshViewHolder;
import cn.bingoogolapple.refreshlayout.BGARefreshLayout;
import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.util.ConvertUtils;
import okhttp3.Request;
import okhttp3.Response;

public class WorkshopMonthPlanActivity extends ToolBarActivity {

    @BindView(R.id.tv_month)
    TextView tvMonth;
    @BindView(R.id.wv)
    WaveView wv;
    @BindView(R.id.wv2)
    WaveView wv2;

    @BindView(R.id.nest_scrollview2)
    NestedScrollView nestScrollview2;
    @BindView(R.id.bga_refresh)
    BGARefreshLayout bgaRefresh;
    @BindView(R.id.bottom_navigation_view)
    BottomNavigationView bottomNavigationView;
    @BindView(R.id.tv_title)
    LinearLayout tvTitle;
    @BindView(R.id.lv)
    RecyclerView lv;
    CommonAdapter<DeviceHouseMonthDayPlanEntity> adapter;
    List<DeviceHouseMonthDayPlanEntity> list = new ArrayList<>();
    @BindView(R.id.mMangeNodata)
    TextView mMangeNodata;
    @BindView(R.id.nest_scrollview)
    NestedScrollView nestScrollview;
    @BindView(R.id.tv_collect)
    TextView tvCollect;
    @BindView(R.id.tv_finish)
    TextView tvFinish;
    @BindView(R.id.app_layput)
    AppBarLayout appLayput;
    @BindView(R.id.lineChart)
    LineChart lineChart;
    DeviceHouseMonthDayPlanEntity MonthItemBean = new DeviceHouseMonthDayPlanEntity();

    DeviceHouseMonthPlanEntity bean=new DeviceHouseMonthPlanEntity();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_workshop_month_plan);
        ButterKnife.bind(this);
        initIntent();
        initView();
    }

    private void initIntent() {
        if (getIntent().getStringExtra("id")!=null){
            departmentId = getIntent().getStringExtra("id");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if ((boolean) SPUtils.get(getApplicationContext(),baseEnum.update(),false)){
//            SPUtils.put(getApplicationContext(),baseEnum.update(),false);
//            customer(1, 1, "");
//        }
        if (getIntent().getSerializableExtra("entity")!=null){
            DeviceHouseMonthPlanEntity entity= (DeviceHouseMonthPlanEntity) getIntent().getSerializableExtra("entity");
            tvMonth.setText(entity.getMonth());
            departmentId=entity.getDepartmentId()+"";
            customer(1,1,"");
        }
        else {
            customer(1,1,"");

        }



    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.toolbar_add_edit_delete, menu);
        MenuItem menuItem = menu.findItem(R.id.menu_add);
        MenuItem menuItem1 = menu.findItem(R.id.menu_edit);
        MenuItem menuItem2 = menu.findItem(R.id.menu_delete);

        if (!PermissonUtils.contains(this, baseEnum.has(PermEnum.ADD))) {
            menuItem.setVisible(false);
        } if (!PermissonUtils.contains(this, baseEnum.has(PermEnum.EDIT))) {
            menuItem1.setVisible(false);
        } if (!PermissonUtils.contains(this, baseEnum.has(PermEnum.DELETE))) {
            menuItem2.setVisible(false);
        }
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            Bundle bundle=new Bundle();

            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_add:
                        bundle.putString("id", getIntent().getStringExtra("id"));
                        bundle.putString("name", getIntent().getStringExtra("name"));

                        IntentUtils.startActivity(WorkshopMonthPlanActivity.this,WorkshopMonthPlanAddActivity.class,bundle);
                        break;
                    case R.id.menu_edit:
                        if (list.size()==0) {
                            ToastUtil.makeText(getApplicationContext(),"当前月份暂无工作计划");

                        }
                        else {
                            bundle.putSerializable("list", (Serializable) list);
                            bundle.putSerializable("bean", bean);
                            IntentUtils.startActivity(WorkshopMonthPlanActivity.this, WorkshopMonthPlanEditActivity.class, bundle);
                        }
                        break;
                    case R.id.menu_delete:
                        if (list.size()==0) {
                            ToastUtil.makeText(getApplicationContext(),"当前月份暂无工作计划");

                        }
                        else {
                            BaseNetUtil.actionDialog(WorkshopMonthPlanActivity.this, NewBaseUrl.devicehousemonthplan_delete, list.get(0).getMonthPlanId() + "", token, "删除" + baseEnum.name, () -> customer(1, 1, ""));

                        }
                        break;





                }
                return false;
            }
        });

        return true;
    }
    private void initView() {
        if (TimeUtil.getNowMonth()<10){
            tvMonth.setText(TimeUtil.getNowYear()+"-0"+TimeUtil.getNowMonth());

        }
        else
        {tvMonth.setText(TimeUtil.getNowYear()+"-"+TimeUtil.getNowMonth());}
//        customer(1, 1, "");
        baseEnum = BaseEnum.WORKSHOPMONTHPLAN;
        initToolBar(baseEnum.name);

        bgaRefresh.setRefreshViewHolder(new BGANormalRefreshViewHolder(MyApplication.getInstance(), false));

        bgaRefresh.setDelegate(new BGARefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
                if (NetworkUtils.checkNetState(getApplicationContext())) {
                    // 如果网络可用，则加载网络数据
                    customer(1, 1, "");
                } else {
                    // 网络不可用，结束下拉刷新
                    bgaRefresh.endRefreshing();
                }
            }

            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
                return false;
            }
        });
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_data:
                        ViewUtil.visible(nestScrollview, tvTitle);
                        ViewUtil.gone(nestScrollview2);


                        break;
                    case R.id.menu_chart:
                        ViewUtil.gone(nestScrollview, tvTitle);
                        ViewUtil.visible(nestScrollview2);
                        appLayput.setExpanded(true,false);


                        break;
                }
                return true;

            }
        });

        appLayput.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (verticalOffset==0){
                                        bgaRefresh.setPullDownRefreshEnable(true);

                }
                else {
                    bgaRefresh.setPullDownRefreshEnable(false);

                }
            }
        });




        initAdapter();
        lv.setAdapter(adapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false) {
        };
        lv.setLayoutManager(linearLayoutManager);
    }

    private void initAdapter() {
        adapter = new CommonAdapter<DeviceHouseMonthDayPlanEntity>(this, R.layout.item_workshop_month_plan, list) {
            @Override
            protected void convert(ViewHolder holder, DeviceHouseMonthDayPlanEntity item, final int position) {
//                holder.setText(R.id.tv_code, item.getSendworkorderEntity().getSendworkCode());
                
                holder.setText(R.id.tv_date, item.getDay().substring(5));
                holder.setText(R.id.tv_plan, item.getPlanOutput() + "");
                holder.setText(R.id.tv_collect, item.getReportOutput() + "");
                holder.setText(R.id.tv_finish, item.getFinishCount() + "");
                Button button = holder.getView(R.id.btn);
                if(item.getHasConfigDayPlan().equals(0)){
button.setBackground(getResources().getDrawable(R.drawable.selector_button_oreange));
//普通的设置无效
                    ColorStateList color = getResources().getColorStateList(R.color.selector_textcolor_orange);

button.setTextColor(color);
button.setText("去配置");
button.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        if (ViewUtil.hasPermiison(getApplicationContext(),BaseEnum.WORKSHOPDAYPLAN.has(PermEnum.ADD))) return;
        Bundle bundle = new Bundle();
        bundle.putSerializable("bean", item);
        bundle.putSerializable("beanParent", bean);

        IntentUtils.startActivity(WorkshopMonthPlanActivity.this, WorkshopDayPlanAddActivity.class, bundle);
    }
});
                }
                else if (item.getHasConfigDayPlan().equals(1)){
                    button.setBackground(getResources().getDrawable(R.drawable.selector_button_blue));
                    ColorStateList color = getResources().getColorStateList(R.color.selector_textcolor_blue);

                    button.setTextColor(color);
                    button.setText("日计划");
                    button.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("bean", item);
                            bundle.putString("id", bean.getDepartmentId()+"");
                            bundle.putSerializable("beanParent", bean);
                            IntentUtils.startActivity(WorkshopMonthPlanActivity.this, WorkshopDayPlanActivity.class, bundle);
                        }
                    });
                }

            }
        };
    }




    @OnClick(R.id.tv_month)
    public void onViewClicked() {
        onYearMonthPicker();
    }

    public void onYearMonthPicker() {
        DatePicker picker = new DatePicker(this, DatePicker.YEAR_MONTH);
//        picker.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
//        picker.setWidth((int) (picker.getScreenWidthPixels() * 0.6));
        picker.setCanceledOnTouchOutside(true);
        picker.setUseWeight(true);
        picker.setTopPadding(ConvertUtils.toPx(this, 10));
        picker.setRangeStart(TimeUtil.getNowYear() - 2, 1, 14);
        picker.setRangeEnd(TimeUtil.getNowYear() + 1, 12, 11);
        picker.setSelectedItem(TimeUtil.getNowYear(), TimeUtil.getNowMonth());
        picker.setOnDatePickListener(new DatePicker.OnYearMonthPickListener() {
            @Override
            public void onDatePicked(String year, String month) {
                tvMonth.setText(year + "-" + month);
                customer(1,1,"");
            }
        });
        picker.show();
    }




    public void customer(Integer page, final Integer type, String search) {
        if (dialog != null) {
            dialog.dismiss();
        }
        OkHttpUtils
                .get(NewBaseUrl.devicehousemonthplan_appselectlist)
                .params("token", token)
                .params("month", tvMonth.getText().toString())
                .params("departmentId", departmentId)

                .execute(new StringLoadingCallback(this) {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", baseEnum.name + ": " + result);
                        if (type == 1) {
                            list.clear();
                        }
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");
                        ViewUtil.lagout(code, getApplicationContext());
                        if (code == 0) {

                            List<DeviceHouseMonthDayPlanEntity> jsonArray = new ArrayList<DeviceHouseMonthDayPlanEntity>(JsonExcludeNull.parseArrayExcludeNull(jsonObj.getString("list"), DeviceHouseMonthDayPlanEntity.class));
bean= JSON.parseObject(jsonObj.getString("entity"), DeviceHouseMonthPlanEntity.class);;
                            list.addAll(jsonArray);

                            if (list.size() == 0) {
                                mMangeNodata.setVisibility(View.VISIBLE);
                            } else {
                                mMangeNodata.setVisibility(View.GONE);
                            }
                            adapter.notifyDataSetChanged();
                            initData();
//                            StaticsCount count = JSON.parseObject(Jpage.getString("staticsCount"), new TypeReference<StaticsCount>() {});
//                            tvSelect0.setText("待点检(" + count.getCount0() + ")");
//                            tvSelect1.setText("待审核(" + count.getCount1() + ")");
//                            tvSelect2.setText("已审核(" + count.getCount2() + ")");


                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                        bgaRefresh.endRefreshing();
                    }
                });
    }

    private void initData() {
        try {
            float collect_total = 0, finish_total = 0, plan_total = 0;
            float[] collect = new float[list.size()];
            float[] finish = new float[list.size()];
            String[] date=new String[list.size()];
            if (list.size()!=0) {
                for (int i=0;i<list.size();i++) {
                    DeviceHouseMonthDayPlanEntity bean=list.get(i);
                    collect_total = collect_total + bean.getReportOutput();
                    finish_total = finish_total + bean.getFinishCount();
                    plan_total = plan_total + bean.getPlanOutput();
                    collect[i]=bean.getReportOutput();
                    finish[i]=bean.getFinishCount();
    date[i]=bean.getDay();
                }
                tvCollect.setText((int) collect_total + "/" + (int) plan_total);
                tvFinish.setText((int) finish_total + "/" + (int) plan_total);
                int collectRate = 0, finishRate = 0;
                if (plan_total != 0) {
                    collectRate = (int) ((collect_total / plan_total) * 100);
                    finishRate = (int) ((finish_total / plan_total) * 100);
                    wv.setProgress(collectRate);
                    wv2.setProgress(finishRate);
                }
                line(date,collect,finish);
            }
            else
            {
                tvCollect.setText((int) 0 + "/" + (int) 0);
                tvFinish.setText((int) 0 + "/" + (int) 0);
                wv.setProgress(0);
                wv2.setProgress(0);
                initLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void initLine() {
        lineChart.setDrawGridBackground(false);

        // no description text
        lineChart.getDescription().setEnabled(false);

        // enable touch gestures
        lineChart.setTouchEnabled(true);

        // enable scaling and dragging
        lineChart.setDragEnabled(true);
        lineChart.setScaleEnabled(true);
        // mChart.setScaleXEnabled(true);
        // mChart.setScaleYEnabled(true);
        lineChart.getAxisRight().setEnabled(false);


        // if disabled, scaling can be done on x- and y-axis separately
        lineChart.setPinchZoom(true);
        lineChart.clear();
    }

    public void line(String[] str, float[] content, float[] content2) {
        initLine();
        String date[]=str.clone();

        String days[]=str ;
        for (int i=0;i<days.length;i++){
            days[i]=days[i].substring(days[i].length()-2);
        }
        ArrayList<Entry> yVals1 = new ArrayList<Entry>();
        for (int i = 0; i < content.length; i++) {
            yVals1.add(new Entry(i, content[i]));
        }

        ArrayList<Entry> yVals2 = new ArrayList<Entry>();

        for (int i = 0; i < content2.length; i++) {

            yVals2.add(new Entry(i, content2[i]));

        }


//        int ssmax = (int) max;
        try {
            lineChart.setVisibility(View.VISIBLE);

            LineDataSet set1, set2, set3;

            if (lineChart.getData() != null &&
                    lineChart.getData().getDataSetCount() > 0) {
                set1 = (LineDataSet) lineChart.getData().getDataSetByIndex(0);
                set2 = (LineDataSet) lineChart.getData().getDataSetByIndex(1);
                set1.setValues(yVals1);
                set2.setValues(yVals2);
                lineChart.getData().notifyDataChanged();
                lineChart.notifyDataSetChanged();
                lineChart.animateXY(1000, 1000);
                lineChart.getData().notifyDataChanged();

            } else {
                // create a dataset and give it a type
                set1 = new LineDataSet(yVals1, "月系统采集");

                set1.setAxisDependency(YAxis.AxisDependency.LEFT);
                set1.setColor(getResources().getColor(R.color.line_bule));
                set1.setCircleColor(getResources().getColor(R.color.line_bule));
                set1.setLineWidth(2f);
                set1.setCircleRadius(3f);
                set1.setFillAlpha(65);
                set1.setFillColor(getResources().getColor(R.color.line_bule));
                set1.setHighLightColor(getResources().getColor(R.color.line_bule));
                set1.setDrawCircleHole(false);
                set1.setDrawValues(false);
                set1.setDrawCircles(true);
                //set1.setFillFormatter(new MyFillFormatter(0f));
                //set1.setDrawHorizontalHighlightIndicator(false);
                //set1.setVisible(false);
                //set1.setCircleHoleColor(Color.WHITE);
                // create a dataset and give it a type
                set2 = new LineDataSet(yVals2, "月完工数量");
                set2.setAxisDependency(YAxis.AxisDependency.LEFT);
                set2.setColor(getResources().getColor(R.color.line_green));
                set2.setCircleColor(getResources().getColor(R.color.line_green));
                set2.setLineWidth(2f);
                set2.setCircleRadius(3f);
                set2.setFillAlpha(65);
                set2.setFillColor(getResources().getColor(R.color.line_green));
                set2.setDrawValues(false);
                set2.setDrawCircles(true);

                set2.setDrawCircleHole(false);
                set2.setHighLightColor(Color.rgb(244, 117, 117));
                //set2.setFillFormatter(new MyFillFormatter(900f));
                YAxis leftAxis = lineChart.getAxisLeft();
                leftAxis.setAxisMinimum(0f);
                XAxis xAxis = lineChart.getXAxis();
                LabelFormatter labelFormatter = new LabelFormatter(days);
                xAxis.setValueFormatter(labelFormatter);
                xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
//                横坐标粒度 缩放
                xAxis.setAxisMinimum(0f);

                xAxis.setGranularity(1f);

                if (str.length<=6){
                    xAxis.setLabelCount(str.length);
                }

                DoubleMarkerView mv = new DoubleMarkerView(WorkshopMonthPlanActivity.this, date,content,content2);
                mv.setChartView(lineChart); // For bounds control
                lineChart.setMarker(mv);

                // create a data object with the datasets
                com.github.mikephil.charting.data.LineData data = new com.github.mikephil.charting.data.LineData(set1, set2);
                data.setValueTextColor(Color.BLACK);
                data.setValueTextSize(9f);
                // set data
                lineChart.setData(data);
                lineChart.animateXY(1000, 1000);

            }


        } catch (Exception e) {
        }

    }
    class LabelFormatter implements IAxisValueFormatter {
        private final String[] mLabels;

        public LabelFormatter(String[] labels) {
            mLabels = labels;
        }

        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            try {

                return mLabels[(int) value];
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }

        }
    }

}
